﻿/*******************************************************
Copyright © 2007-2009 Active Technologies Group, Inc. (ATGi)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ATGi.CS.BrightCove;
using System.Web.UI;
using System.ComponentModel;
using CommunityServer.Controls;
using CommunityServer.Components;

namespace ATGi.CS.BrightCove.Controls
{
    public class BrightCoveVideoList : CommunityServer.Controls.PreTemplatedListBase
    {
        BrightCoveVideoQuery _queryOverrides;
        /// <summary>
        /// Overrides from the default implicit query
        /// </summary>
        /// <remarks>The JSON deserialization process runs into problems with large response streams. Therefore, a page size of less than 50 is recommended.</remarks>
        [
        Browsable(false),
        DefaultValue(null),
        Description("Overrides from the default implicit query"),
        PersistenceMode(PersistenceMode.InnerProperty),
        ]
        public virtual BrightCoveVideoQuery QueryOverrides
        {
            get { return _queryOverrides; }
            set
            {
                if (_queryOverrides != null)
                    this.Controls.Remove(_queryOverrides);

                _queryOverrides = value;
                if (_queryOverrides != null)
                    this.Controls.Add(_queryOverrides);
            }
        }

        protected override void AddPropertyControls(bool dataBinding)
        {
            if (this.QueryOverrides != null)
                this.Controls.Add(this.QueryOverrides);

            base.AddPropertyControls(dataBinding);
        }
        
        private bool _isImplicitDataSource = true;
        List<BrightCoveVideo> _videos;
        public override object DataSource
        {
            get
            {
                if (_videos == null)
                {
                    BrightCoveResultSet<BrightCoveVideo> results = new BrightCoveResultSet<BrightCoveVideo>() ;
                    BrightCoveVideoQuery query = new BrightCoveVideoQuery();
                    if (this.QueryOverrides != null)
                    {
                        query = this.QueryOverrides;
                        switch (this.QueryOverrides.QueryType)
                        {
                            case BrightCoveVideoQueryType.All:
                                results = BrightCoveVideos.FindAllVideos(query.PageSize, query.PageIndex, query.SortBy, query.SortOrder, query.Fields);
                                break;
                            case BrightCoveVideoQueryType.Campaign:
                                results = BrightCoveVideos.FindVideosByCampaignId(query.CampaignID, query.PageSize, query.PageIndex, query.SortBy, query.SortOrder, null);
                                break;
                            case BrightCoveVideoQueryType.Related:
                                results = BrightCoveVideos.FindRelatedVideos(query.VideoID, query.PageSize, query.PageIndex, null);
                                break;
                            case BrightCoveVideoQueryType.Tags:
                                break;
                            case BrightCoveVideoQueryType.Text:
                                results = BrightCoveVideos.FindVideosByText(query.SearchText, query.PageSize, query.PageIndex, query.SortBy, query.SortOrder, null);
                                break;
                            case BrightCoveVideoQueryType.User:
                                results = BrightCoveVideos.FindVideosByUserId(query.UserID, query.PageSize, query.PageIndex, query.SortBy, query.SortOrder, null);
                                break;
                        }
                    }
                    else
                    {
                        results = BrightCoveVideos.FindAllVideos(-1, -1, BCSortByType.PUBLISH_DATE, BCSortOrder.ASC,query.Fields);
                    }
                    if (this.QueryOverrides != null && this.QueryOverrides.Pager != null)
                    {
                        this.QueryOverrides.Pager.PageIndex = query.PageIndex;
                        this.QueryOverrides.Pager.PageSize = query.PageSize;
                        this.QueryOverrides.Pager.TotalRecords = results.TotalRecords;
                        this.QueryOverrides.Pager.OnPageIndexChanged += new PagerEventHandler(this.PageIndexChanged);
                        this.QueryOverrides.Pager.DataBind();
                    }
                    _videos = results.Items;
                }
                return _videos;
            }
            set
            {
                if (value is List<BrightCoveVideo>)
                {
                    _videos = value as List<BrightCoveVideo>;
                    _isImplicitDataSource = false;
                    RequiresDataBinding = true;
                    OnDataPropertyChanged();
                }
                else if (value == null)
                {
                    _videos = null;
                    _isImplicitDataSource = true;
                    OnDataPropertyChanged();
                    RequiresDataBinding = true;
                }
                else
                    throw new InvalidCastException("DataSource must be a valid List<BrightCoveVideo> object");
            }
        }

        public override void FlagForDataBinding()
        {
            this.DataSource = null;
            base.FlagForDataBinding();
        }

        /// <summary>
        /// Handler for IPager.OnPageIndexChanged events.
        /// </summary>
        /// <param name="sender">The IPager initiating the event.</param>
        /// <param name="e">The <see cref="CommunityServer.Controls.PagerEventArgs"/> instance containing the event data.</param>
        protected void PageIndexChanged(IPager sender, PagerEventArgs e)
        {
            if (_isImplicitDataSource)
                FlagForDataBinding();
        }


        protected override void BindDefaultItemContent(CommunityServer.Controls.PreTemplatedListBase.ListItemTemplateListItem listItem, System.Web.UI.IDataItemContainer dataItemContainer)
        {
            BrightCoveVideo item = dataItemContainer.DataItem as BrightCoveVideo;
            if (item != null)
            {
                BrightCoveVideoData bcv = new BrightCoveVideoData();
                bcv.DataSource = item;
                bcv.Text = item.name;
                bcv.LinkTo = BrightCoveVideoLinkTo.Video;
                listItem.Controls.Add(bcv);
            }
        }
    }
}
